package com.sinosoft.hydra.um.services.component.message;

import com.sinosoft.hydra.logging.LogModules;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.permission.TMessage;
import com.sinosoft.hydra.um.domain.permission.TMessageReceiver;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2015/8/25.
 */
@Service
public class ToEmail implements MessageSendProxy {

    @Value("#{propertiesReader['email.host']}")
    private String mailHost;
    @Value("#{propertiesReader['email.user.name']}")
    private String mailName;
    @Value("#{propertiesReader['email.user.password']}")
    private String mailPassword;

    public boolean isValid(String type){
        return BaseConstant.MessageSendType.MESSAGE_SEND_TYPE_EMAIL.name().equals(type);
    }

    public boolean send(TMessage tMessage, TMessageReceiver messageReceiver) {
        try {
            Email email = new SimpleEmail();
            email.setHostName(mailHost);
            email.setAuthentication(mailName, mailPassword);
            email.setCharset("UTF-8");
            email.setFrom(tMessage.getSenderName(), "");//设置发件人
            email.addTo(messageReceiver.getReceiver());//设置收件人
            email.setSubject(tMessage.getSendTitle());//设置主题
            email.setMsg(tMessage.getSendContent());//设置邮件内容
            email.send();
            return true;
        } catch (Exception ex) {
            LoggerFactory.getLogger(LogModules.TRACE_LOGGER).error("发送邮件出现错误，发送给用户{}失败，失败原因{}", messageReceiver.getReceiver(), ex.getMessage());
            return false;
        }
    }
}
